<?php

namespace App\Services;

use App\Models\ForeignSpeakerCollection;
use App\Models\ForeignSpeakerCollectionPivot;
use App\Models\ForeignSpeakerShareLog;
use App\Models\Links;
use App\Models\Project;
use App\Models\ProjectMeeting;
use App\Models\ProjectMeetingInvitationSpeaker;
use App\Models\Speaker;
use App\Models\UserLoginErrorRecord;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Throwable;

/**
 * 项目服务
 *
 * @Author hechengwei
 * @email chichiooo@sina.com
 * @DateTime 2024-09-23
 */
class ProjectService
{
    /**
     * 服务案例
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-09-23
     * @return void
     */
    public static function serviceCase()
    {
        // with(['invitationSpeaker' => function ($query) {
        //     $query->with(['speakerDetail' => function ($query) {
        //         $query->select('id', 'name', 'name_en', 'photo');
        //     }])->select('id', 'project_id', 'project_meeting_id', 'speaker_id');
        // }])
        //     ->
        $result = Project::where(['project_status' => 2, 'recommend' => 1, 'is_display' => 1])
            ->whereNull('delete_time')
            ->select('id', 'project_name', 'company_name')
            // ->limit(8)
            ->get();
        foreach ($result as $key => &$val) {
            // 邀请状态为1的数据
            $speaker = ProjectMeetingInvitationSpeaker::where('project_id', $val['id'])->where('invitation_status', 1)->select('id', 'project_id', 'project_meeting_id', 'speaker_id')->get();
            $speakerId = $speaker->pluck('speaker_id');
            $val['photo'] = Speaker::whereIn('id', $speakerId)->limit(3)->pluck('photo');
            // 统计会议数量
            $val['meetingCount'] = ProjectMeeting::where(['project_id' => $val['id'], 'status' => '2', 'is_display' => 1])->count();
            // 统计讲者数量
            $val['speakerCount'] = ProjectMeetingInvitationSpeaker::where(['project_id' => $val['id'], 'invitation_status' => 1, 'is_display' => 1])->count();
        }

        return $result ?? [];
    }

    /**
     * 获取项目案例详情
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-12-16
     * @param [type] $id
     * @return void
     */
    public static function getProjectDetail($id)
    {
        $project = Project::where('id', $id)->select('id', 'project_name', 'company_name')->first();

        // 关联project_meeting表
        $project->load(['meeting' => function ($query) {
            //  // 关联project_meeting_invitation_speaker表
            $query->with([
                'invitationSpeaker' => function ($query) {
                    $query->with([
                        'speakerDetail' => function ($query) {
                            $query->select('id', 'name', 'title', 'remarks', 'remarks_en', 'photo', 'tags', 'tags_en', 'medical_category', 'medical_category_cn', 'medical_category_en');
                        },
                        'uploadDetail' => function ($query) {
                            $query->select('id', 'invitation_speaker_id', 'meeting_type', 'meeting_time_bj', 'meeting_time_en', 'meeting_start_time', 'meeting_end_time', 'meeting_info_is_display', 'meeting_materiel', 'meeting_screen_recording', 'meeting_photo', 'meeting_materiel_is_display', 'meeting_ppt', 'meeting_ppt_is_display');
                        }
                    ])->select('id', 'project_id', 'project_meeting_id', 'speaker_id', 'speaker_name', 'speaker_email', 'meeting_type', 'invitation_status')->where('invitation_status', 1);
                }
            ])->select('id', 'project_id', 'meeting_name', 'status')->where('status', 2);
        }]);
        // dd($project);
        return $project;
    }

    /**
     * 案例库列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-09-25
     * @param [type] $payload
     * @return void
     */
    public static function getProjectCaseList($payload)
    {

        $where = function ($query) use ($payload) {
            $query->where('project_status', 2);
            $query->where('is_display', 1);
            if (isset($payload['project_name']) && $payload['project_name'] != '') {
                $query->where('project_name', 'like', '%' . $payload['project_name'] . '%');
            }
        };

        $list = Project::where($where)
            ->whereNull('delete_time')
            ->select('id', 'project_name', 'company_name')
            ->orderBy('create_time', 'desc')
            ->paginate($payload['limit']);

        foreach ($list as $key => &$val) {
            $speakerId = ProjectMeetingInvitationSpeaker::where('project_id', $val['id'])->where('invitation_status', 1)->pluck('speaker_id')->toArray();
            $val['photo'] = Speaker::whereIn('id', $speakerId)->limit(3)->pluck('photo');
            // 统计会议数量
            $val['meetingCount'] = ProjectMeeting::where(['project_id' => $val['id'], 'status' => '2', 'is_display' => 1])->count();
            // 统计讲者数量
            $val['speakerCount'] = ProjectMeetingInvitationSpeaker::where(['project_id' => $val['id'], 'invitation_status' => 1, 'is_display' => 1])->count();
        }
        return $list;
    }

    /**
     * 根据项目id获取项目进度
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-10-09
     * @param [type] $projectId
     * @return void
     */
    public static function getProjectProgress($projectId)
    {
        $projectProgress = 1;
        $projectMeeting = ProjectMeeting::where('project_id', $projectId)->get();

        // 只有项目，没有创建会议，立项阶段
        if ($projectMeeting->isEmpty()) {
            // 立项阶段
            return $projectProgress = 1;
        }

        $projectMeetingInvitationSpeakerId = ProjectMeetingInvitationSpeaker::where('project_id', $projectId)->pluck('id');

        // 查询项目对应邀请讲者的主键id，去查询对应填充的资料
        if (!$projectMeetingInvitationSpeakerId->isEmpty()) {

            // 沟通阶段
            return $projectProgress = 3;
        }

        // 统计有多少会议
        $meetingCount = $projectMeeting->count();
        $count = 0;
        // 如果后期要修改成百分比，可以详细计算
        foreach ($projectMeeting as $key => $val) {
            if ($val['confirm_invitation'] != 0 || $val['total_invitation'] != 0) {
                if ($val['confirm_invitation'] == $val['total_invitation']) {
                    $count += 1;
                }
            }
        }

        // @todo 详细计算步骤
        if ($count >= 1) {
            return $projectProgress = 2;
        }

        return $projectProgress;
    }

    /**
     * 登录错误记录
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-12-25
     * @param [type] $data
     * @return void
     */
    public static function recordLoginError($data)
    {

        if (!empty($data)) {
            $errorRecordCount = 0;
            $lockCount = 0;
            $errorRecord = UserLoginErrorRecord::where('username', $data['username'])->whereNull('delete_time')->get();

            if (!$errorRecord->isEmpty()) {
                $errorRecordCount = $errorRecord->count();
                // 当密码错误次数大于配置次数时，判断是第几次锁定账户，进行叠加
                if ($errorRecordCount > sysConfig('password_error_count')) {
                    // 锁定的数据
                    $lockData = $errorRecord->where('lock_status', 1);
                    // 没有锁定数据，第一次锁定
                    if ($lockData->isEmpty()) {
                        $data['ip'] = request()->ip();
                        $data['lock_status'] = 1;
                        $data['lock_time'] = sysConfig('lock_time');
                        $data['lock_count'] = 1;
                        $data['create_time'] = Carbon::now();
                        $data['update_time'] = Carbon::now();
                    } else {
                        // 有锁定数据，// 判断第几次锁定
                        $data['ip'] = request()->ip();
                        $data['lock_status'] = 1;
                        $data['lock_time'] = sysConfig('lock_time') * ($lockData->count() + 1);
                        $data['lock_count'] = $lockData->count() + 1;
                        $data['create_time'] = Carbon::now();
                        $data['update_time'] = Carbon::now();
                    }
                } else {
                    // 小于配置错误次数，记录错误信息
                    $data['ip'] = request()->ip();
                    $data['lock_status'] = 0;
                    $data['create_time'] = Carbon::now();
                    $data['update_time'] = Carbon::now();
                }
            } else {
                // 为空的时候是第一次错误
                $data['ip'] = request()->ip();
                $data['lock_status'] = 0;
                $data['create_time'] = Carbon::now();
                $data['update_time'] = Carbon::now();
            }

            UserLoginErrorRecord::create($data);
        }
    }

    /**
     * 判断用户是否被锁定
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-12-25
     * @param [type] $user
     * @return array
     */
    public static function checkLoginIsLock($data)
    {
        $result = [];
        // 获取所有删除与未删除登录错误记录
        $list = UserLoginErrorRecord::where('username', $data['username'])->get();
        // 判断当前用户是否被锁定,并排序
        $currentUser = $list->whereNull('delete_time')->where('lock_status', 1)->sortBy('lock_count');
        // 如果有未删除的错误记录
        if (!$currentUser->isEmpty()) {
            // 返回最后一次锁定的数据
            $res = $currentUser->last()->toArray();
            // 锁定失效时间
            $expirationTime = Carbon::createFromFormat('Y-m-d H:i:s', $res['create_time'])->addMinutes($res['lock_time']);

            $now = Carbon::now();
            $isAfter = $now->isAfter($expirationTime);

            if ($isAfter) {
                return ['state' => false, 'data' => ['lock_time' => $res['lock_time'], 'error_count' => sysConfig('password_error_count'), 'ip_lock' => false]];
            } else {
                return ['state' => true, 'data' => ['lock_time' => $res['lock_time'], 'error_count' => sysConfig('password_error_count'), 'ip_lock' => false]];
            }
            // $result = ['state' => true, 'lock_count' => $res['lock_count'], 'lock_ip' => ''];
        } else {
            // 如果没有未删除的病历记录
            $noDeleteList = UserLoginErrorRecord::where('ip', request()->ip())->whereDay('create_time', Carbon::today())->get();
            // 判断是否是同一个IP地址是否大于配置次数，禁止再次访问登录
            if ($noDeleteList->count() > 5) {
                return ['state' => true, 'data' => ['lock_time' => '', 'error_count' => '', 'ip_lock' => true]];
            } else {
                return ['state' => false, 'data' => ['lock_time' => '', 'error_count' => '', 'ip_lock' => false]];
            }
        }

        return $result;
    }



    /**
     * 登录成功之后把失败记录删除
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-12-25
     * @param [type] $data
     * @return void
     */
    public static function loginSuccess($data)
    {
        UserLoginErrorRecord::where('username', $data['username'])->update([
            'delete_time' => Carbon::now()
        ]);
    }
}
